/**
 * function getInitialLocation - Gets the initial GPS coordinate for the current position of the user (needs user clearance).
 * 
 * @author PAF 
 * */
function getInitialLocation() {
	if (navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(handleInitialSuccess, handleError) ;
	}
	else {
		//TODO: If the user hasn't access to the Internet or if it does not give clearance for accessing its current position, do something...
	}
}

/**
 * function handleInitialSuccess - If the application was able to access the user's current position, the function initializes the map interface and gets
 * 									the list of nearby places from Foursquare. It is called from the getInitialPosition function
 * 
 * @param position The GPS coordinate for the current position (initial) of the user
 * @author PAF
 * */
function handleInitialSuccess(position) {
	currentCoord = position.coords.latitude + "," + position.coords.longitude ;
	initializeMap() ;
}

/**
 * function handleError - If the GPS coordinate of the user's current position cannot be determined, this function handles the error 
 * 
 * @param error  
 * @author PAF
 * */
function handleError(error) {
	switch(error.code) {
    case error.PERMISSION_DENIED:
    	//TODO: If user did not grant permission to access its current location, do something...
    	break;
    case error.POSITION_UNAVAILABLE:
    	//TODO: If the position is unavailable or cannot be resolved, do something...
      break;
    case error.TIMEOUT:
    	//TODO: If the access takes to long (timeout), do something...
      break;
    case error.UNKNOWN_ERROR:
    	//TODO: If there is any other error, do something...
      break;
    }
}

function initGetDirections() {
	hideAllContents() ;
	if (isGetDirectionsInitialized === 0)
		hideContentWithCallback($("#mediumRightContent"), callGetDirectionsHTML) ;
	else {
		if (destinationCoord)
        	$("#destination").val(destinationCoord.lat + "," + destinationCoord.lng) ;
	}
}

function callGetDirectionsHTML() {
	$("#mediumRightContent").empty() ;
	var url = "getDirections.html" ;
	htmlAjaxRequest(url, showGetDirections) ;
}

function showGetDirections(data) {
    $("#mediumRightContent").append("<div id=\"mediumRightTitle\"><h1>Get Directions</h1></div>") ;
    $("#mediumRightContent").append(data);
    var currentTime = new Date() ;
    $("#time").datetimepicker({
    	dateFormat: "yy-mm-dd",
    	timeFormat: "HH:mm",
    	defaultValue: currentTime.getFullYear + "-" + (currentTime.getMonth() + 1) + "-" + currentTime.getDate() + " " + currentTime.getHours() + ":" + currentTime.getMinutes()
    }) ;
    showContent($("#mediumRightContent")) ;
}

function getDirectionsRoutino() {
	isGetDirectionsInitialized = 1 ;
	$("#popup").empty() ;
	$("#popup").append("<img id='loader' src='../images/ajax-loader.gif' />") ;
	centerPopup("#popup") ;
    loadPopup("#popup") ;
	
	var str = "";
	if (waypointCounter === 0) {
		str = "origin=" + $("#origin").val() + "&destination=" + $("#destination").val() + "&time=" + $("#time").val() ;
	}
	else {
		var waypoints = "";
		for (var i = 0; i < waypointCounter; i++) {
			if (i === 0)
				waypoints += $("#waypoint" + (i+1)).val() ;
			else {
				waypoints += ("!!" + $("#waypoint" + (i+1)).val()) ;
			}
			waypointList[i] = $("#waypoint" + (i+1)).val() ;
		}
		if (waypoints === "undefined") {
			str = "origin=" + $("#origin").val() + "&destination=" + $("#destination").val() + "&time=" + $("#time").val() ;
		}
		else {
			str = "origin=" + $("#origin").val() + "&destination=" + $("#destination").val() + "&waypoints=" + waypoints + "&time=" + $("#time").val() ;
		}
	}
	
	str += "&shortest=" + $('input:radio[name=routeType]:checked').val() ;
	
	if ($("#motorcar").css("opacity") === "1")
		str += "&transportType=motorcar" ;
	else if ($("#psv").css("opacity") === "1")
		str += "&transportType=psv&carSharing=" + $('input:checkbox[name=carSharing]:checked').val() ;
	else if ($("#bicycle").css("opacity") === "1")
		str += "&transportType=bicycle" ;
	else if ($("#foot").css("opacity") === "1")
		str += "&transportType=foot" ;
	else str += "&transportType=" ;
	
	// Reset waypoints
    waypointCounter = 0 ;
	
    var url = "/MobisRoutePlannerV0.3/GetDirectionsRoutino" ;
	if ($("#psv").css("opacity") === "1")
		jsonAjaxRequest(url, str, showPSVRoutes) ;
	else
		jsonAjaxRequest(url, str, showRoute) ;
}

function showRoute(data) {
	var json = jQuery.parseJSON(data) ;
	latlngs = json.route_geometry ;
	
	hideAllContents() ;

	waypointCounter = 0 ;
	

	removePolylines(polyline, polylines) ;
	if (destinationMarker)
		removeMarker(destinationMarker) ;
	if (originMarker)
		removeMarker(originMarker) ;
	deleteMarkers(markers) ;
	
	var destLat = latlngs[latlngs.length - 1][0] ;
	var destLng = latlngs[latlngs.length - 1][1] ;
	
	var originLat = latlngs[0][0] ;
	var originLng = latlngs[0][1] ;
	
	var lat, lng ;
	
	if (waypointList !== []) {
		for (var i = 0; i < waypointList.length; i++) {
			lat = waypointList[i].substring(0, waypointList[i].indexOf(",")) ;
			lng = waypointList[i].substring(waypointList[i].indexOf(",") + 1) ;
			markers[markers.length - 1] = createMarker(lat, lng, "blue") ;
			createMarkerMouseOverPopup(markers[markers.length - 1], 'Waypoint ' + (i + 1), false) ;
		}
	}
	polyline = createPolyline(latlngs, 'red') ;
	destinationMarker = createMarker(destLat, destLng, 'blue') ;
	originMarker = createMarker(originLat, originLng, 'red') ;
	
	createMarkerMouseOverPopup(destinationMarker, 'Destination', false) ;
	createMarkerMouseOverPopup(originMarker, 'Origin', false) ;
	
	map.fitBounds(polyline.getBounds());
	
	isGetDirectionsInitialized = 0 ;
	
	var url = "/MobisRoutePlannerV0.3/GetRouteInstructionsRoutino" ;
	var str = "shortest=" + $('input:radio[name=routeType]:checked').val() ;
	
	jsonAjaxRequest(url, str, showRouteInstructions) ;
}

function showPSVRoutes(data) {
	hideAllContents() ;
	var html ;
	var json = jQuery.parseJSON(data) ;
	segmentsLength = json.segments.length ;
	segments = json.segments ;
	html = json.segments[0].html ;
	
	disablePopup('#popup');
	$("#popup").empty() ;
	$("#popup").append("<h1>Available Routes</h1>") ;
	$("#popup").append(html) ;
	centerPopup("#popup") ;
	loadPopup("#popup") ;
}

function showRouteInstructions(data) {
	disablePopup('#popup');
	$("#bigRightContent").empty() ;
	$("#bigRightContent").append("<div id=\"mediumRightTitle\"><h1>Route Instructions</h1></div>") ;
	$("#bigRightContent").append("<div id='instructionsContainer'></div>") ;
	$("#instructionsContainer").append("<img id='car' class='directionsIcon' src='https://foursquare.com/img/categories_v2/shops/automotive_bg_32.png'/><div id='carLegend' class='legend'></div>") ;
	$("#instructionsContainer").append(data) ;
	showContent($("#bigRightContent")) ;
}

function getPSVDirections(segNum) {
	disablePopup('#popup');
	
	if ((segmentsLength > 1 && segmentCounter == segmentsLength - 1) || (segmentsLength == 1)) {
		segNums += segNum + "," ;
		segNums = segNums.substring(0, segNums.lastIndexOf(",")) ;
		var url = "/MobisRoutePlannerV0.3/GetDirectionsResRobot" ;
		var str = "segments=" + segmentsLength + "&segNums=" + segNums ;
		$("#popup").empty() ;
		$("#popup").append("<img id='loader' src='../images/ajax-loader.gif' />") ;
		centerPopup("#popup") ;
	    loadPopup("#popup") ;
	    
	    segmentCounter = 0 ;
	    segNums = "" ;
	    
		jsonAjaxRequest(url, str, showPSVDirections) ;
	}
	
	if (segmentsLength > 1 && segmentCounter < segmentsLength - 1) {
		segmentCounter++ ;
		var html = segments[segmentCounter].html ;
		segNums += segNum + "," ;
		$("#popup").empty() ;
		$("#popup").append("<h1>Available Routes</h1>") ;
		$("#popup").append(html) ;
		centerPopup("#popup") ;
		loadPopup("#popup") ;
	}
}

function showPSVDirections(data) {
	var json = jQuery.parseJSON(data) ;
	
	removePolylines(polyline, polylines) ;
	if (destinationMarker)
		removeMarker(destinationMarker) ;
	if (originMarker)
		removeMarker(originMarker) ;
	deleteMarkers(markers) ;
	
	$("#bigRightContent").empty() ;
	$("#bigRightContent").append("<div id=\"mediumRightTitle\"><h1>Route Instructions</h1></div>") ;
	var str = "" ;
	var latlngs = [] ;
	var originLat = 0.0 ;
	var originLng = 0.0 ;
	var destLat = 0.0 ;
	var destLng = 0.0 ;
	var error ;
	var segment ;
	var transportType ;
	var marker ;
	
	$("#bigRightContent").append("<div id='instructionsContainer'></div>") ;
	
	for (var i = 0; i < json.route.length; i++) {
		segment = json.route[i].segment ;
		latlngs = segment.route_geometry ;
		transportType = segment.transport_type ;
		destLat = latlngs[latlngs.length - 1][0] ;
		destLng = latlngs[latlngs.length - 1][1] ;
		error = segment.error ;
		
		if (i == 0) {
			originLat = latlngs[0][0] ;
			originLng = latlngs[0][1] ;
			str = "<p> ORIGIN - " + (typeof segment.departure_station_name !== "undefined" ? ("Waypoint " + (i + 1) + ": " + segment.departure_station_name) : ("Waypoint " + (i + 1))) + "</p>" ;
			str += "<p>Latitude: " + originLat + "</p>" ;
			str += "<p>Longitude: " + originLng + "</p>" ;
			originMarker = createMarker(originLat, originLng, 'red') ;
			createMarkerMouseOverPopup(originMarker, str, false) ;
		}

		switch (transportType) {
			case "A": 
				$("#instructionsContainer").append("<img id='air' class='directionsIcon' src='https://foursquare.com/img/categories_v2/travel/airport_bg_32.png'/><div id='airLegend' class='legend'></div>") ;
				$("#instructionsContainer").append("<p>At: " + (typeof segment.departure_station_name !== "undefined" ? (segment.departure_station_name + ", ") : ("Waypoint " + (i + 1) + ", ")) + segment.departure_time + "</p>") ;
				$("#instructionsContainer").append("<p>Action: Take the flight " + (typeof segment.number !== "undefined" ? segment.number : "") + (typeof segment.carrier_name !== "undefined" ? (" of carrier " + segment.carrier_name) : "") + "" + (typeof segment.arrival_station_name !== "undefined" ? (" towards " + segment.arrival_station_name) : (" towards Waypoint " + (i + 2))) + (typeof segment.direction !== "undefined" ? (" (direction: " + segment.direction + ")") : "") + "</p>") ;
				$("#instructionsContainer").append("<p>Expected arrival time: " + segment.arrival_time + "</p>") ;
				polylines[i] = createPolyline(latlngs, 'white') ;
				break ;
			case "B": 
				$("#instructionsContainer").append("<img id='bus' class='directionsIcon' src='https://foursquare.com/img/categories_v2/travel/busstation_bg_32.png'/><div id='busLegend' class='legend'></div>") ;
				$("#instructionsContainer").append("<p>At: " + (typeof segment.departure_station_name !== "undefined" ? (segment.departure_station_name + ", ") : ("Waypoint " + (i + 1) + ", ")) + segment.departure_time + "</p>") ;
				$("#instructionsContainer").append("<p>Action: Take the bus " + (typeof segment.number !== "undefined" ? segment.number : "") + (typeof segment.carrier_name !== "undefined" ? (" of carrier " + segment.carrier_name) : "") + "" + (typeof segment.arrival_station_name !== "undefined" ? (" towards " + segment.arrival_station_name) : (" towards Waypoint " + (i + 2))) + (typeof segment.direction !== "undefined" ? (" (direction: " + segment.direction + ")") : "") + "</p>") ;
				$("#instructionsContainer").append("<p>Expected arrival time: " + segment.arrival_time + "</p>") ;
				polylines[i] = createPolyline(latlngs, 'yellow') ;
				break ;
			case "D": 
				$("#instructionsContainer").append("<img id='airport_bus' class='directionsIcon' src='https://foursquare.com/img/categories_v2/travel/busstation_bg_32.png'/><div id='airportBusLegend' class='legend'></div>") ;
				$("#instructionsContainer").append("<p>At: " + (typeof segment.departure_station_name !== "undefined" ? (segment.departure_station_name + ", ") : ("Waypoint " + (i + 1) + ", ")) + segment.departure_time + "</p>") ;
				$("#instructionsContainer").append("<p>Action: Take the airport bus " + (typeof segment.number !== "undefined" ? segment.number : "") + (typeof segment.carrier_name !== "undefined" ? (" of carrier " + segment.carrier_name) : "") + "" + (typeof segment.arrival_station_name !== "undefined" ? (" towards " + segment.arrival_station_name) : (" towards Waypoint " + (i + 2))) + (typeof segment.direction !== "undefined" ? (" (direction: " + segment.direction + ")") : "") + "</p>") ;
				$("#instructionsContainer").append("<p>Expected arrival time: " + segment.arrival_time + "</p>") ;
				polylines[i] = createPolyline(latlngs, 'yellow') ;
				break ;
			case "E":
				$("#instructionsContainer").append("<img id='airport_taxi' class='directionsIcon' src='https://foursquare.com/img/categories_v2/travel/taxi_bg_32.png'/><div id='airportTaxiLegend' class='legend'></div>") ;
				$("#instructionsContainer").append("<p>At: " + (typeof segment.departure_station_name !== "undefined" ? (segment.departure_station_name + ", ") : ("Waypoint " + (i + 1) + ", ")) + segment.departure_time + "</p>") ;
				$("#instructionsContainer").append("<p>Action: Take the airport taxi " + (typeof segment.number !== "undefined" ? segment.number : "") + (typeof segment.carrier_name !== "undefined" ? (" of carrier " + segment.carrier_name) : "") + "" + (typeof segment.arrival_station_name !== "undefined" ? (" towards " + segment.arrival_station_name) : (" towards Waypoint " + (i + 2))) + (typeof segment.direction !== "undefined" ? (" (direction: " + segment.direction + ")") : "") + "</p>") ;
				$("#instructionsContainer").append("<p>Expected arrival time: " + segment.arrival_time + "</p>") ;
				polylines[i] = createPolyline(latlngs, 'green') ;
				break ;
			case "F": 
				$("#instructionsContainer").append("<img id='ferry' class='directionsIcon' src='https://foursquare.com/img/categories_v2/travel/boat_bg_32.png'/><div id='ferryLegend' class='legend'></div>") ;
				$("#instructionsContainer").append("<p>At: " + (typeof segment.departure_station_name !== "undefined" ? (segment.departure_station_name + ", ") : ("Waypoint " + (i + 1) + ", ")) + segment.departure_time + "</p>") ;
				$("#instructionsContainer").append("<p>Action: Take the ferry " + (typeof segment.number !== "undefined" ? segment.number : "") + (typeof segment.carrier_name !== "undefined" ? (" of carrier " + segment.carrier_name) : "") + "" + (typeof segment.arrival_station_name !== "undefined" ? (" towards " + segment.arrival_station_name) : (" towards Waypoint " + (i + 2))) + (typeof segment.direction !== "undefined" ? (" (direction: " + segment.direction + ")") : "") + "</p>") ;
				$("#instructionsContainer").append("<p>Expected arrival time: " + segment.arrival_time + "</p>") ;
				polylines[i] = createPolyline(latlngs, 'gray') ;
				break ;
			case "G": 
				$("#instructionsContainer").append("<img id='foot' class='directionsIcon' src='../images/walking.png'/><div id='footLegend' class='legend'></div>") ;
				$("#instructionsContainer").append(segment.routino_instructions) ;
				$("#instructionsContainer").append("<p>Expected arrival time: " + segment.arrival_time + "</p>") ;
				polylines[i] = createPolyline(latlngs, 'red') ;
				break ;
			case "J": 
				$("#instructionsContainer").append("<img id='train' class='directionsIcon' src='https://foursquare.com/img/categories_v2/travel/trainstation_bg_32.png'/><div id='trainLegend' class='legend'></div>") ;
				$("#instructionsContainer").append("<p>At: " + (typeof segment.departure_station_name !== "undefined" ? (segment.departure_station_name + ", ") : ("Waypoint " + (i + 1) + ", ")) + segment.departure_time + "</p>") ;
				$("#instructionsContainer").append("<p>Action: Take the train " + (typeof segment.number !== "undefined" ? segment.number : "") + (typeof segment.carrier_name !== "undefined" ? (" of carrier " + segment.carrier_name) : "") + "" + (typeof segment.arrival_station_name !== "undefined" ? (" towards " + segment.arrival_station_name) : (" towards Waypoint " + (i + 2))) + (typeof segment.direction !== "undefined" ? (" (direction: " + segment.direction + ")") : "") + "</p>") ;
				$("#instructionsContainer").append("<p>Expected arrival time: " + segment.arrival_time + "</p>") ;
				polylines[i] = createPolyline(latlngs, 'blue') ;
				break ;
			case "K": 
				$("#instructionsContainer").append("<img id='dock' class='directionsIcon' src='https://foursquare.com/img/categories_v2/travel/highway_bg_32.png'/><div id='dockLegend' class='legend'></div>") ;
				$("#instructionsContainer").append("<p>At: " + (typeof segment.departure_station_name !== "undefined" ? (segment.departure_station_name + ", ") : ("Waypoint " + (i + 1) + ", ")) + segment.departure_time + "</p>") ;
				$("#instructionsContainer").append("<p>Action: Take the ship " + (typeof segment.number !== "undefined" ? segment.number : "") + (typeof segment.carrier_name !== "undefined" ? (" of carrier " + segment.carrier_name) : "") + "" + (typeof segment.arrival_station_name !== "undefined" ? (" towards " + segment.arrival_station_name) : (" towards Waypoint " + (i + 2))) + (typeof segment.direction !== "undefined" ? (" (direction: " + segment.direction + ")") : "") + "</p>") ;
				$("#instructionsContainer").append("<p>Expected arrival time: " + segment.arrival_time + "</p>") ;
				polylines[i] = createPolyline(latlngs, 'gray') ;
				break ;
			case "T": 
				$("#instructionsContainer").append("<img id='taxi' class='directionsIcon' src='https://foursquare.com/img/categories_v2/travel/taxi_bg_32.png'/><div id='taxiLegend' class='legend'></div>") ;
				$("#instructionsContainer").append("<p>At: " + (typeof segment.departure_station_name !== "undefined" ? (segment.departure_station_name + ", ") : ("Waypoint " + (i + 1) + ", ")) + segment.departure_time + "</p>") ;
				$("#instructionsContainer").append("<p>Action: Take the taxi " + (typeof segment.number !== "undefined" ? segment.number : "") + (typeof segment.carrier_name !== "undefined" ? (" of carrier " + segment.carrier_name) : "") + "" + (typeof segment.arrival_station_name !== "undefined" ? (" towards" + segment.arrival_station_name) : (" towards Waypoint " + (i + 2))) + (typeof segment.direction !== "undefined" ? (" (direction: " + segment.direction + ")") : "") + "</p>") ;
				$("#instructionsContainer").append("<p>Expected arrival time: " + segment.arrival_time + "</p>") ;
				polylines[i] = createPolyline(latlngs, 'green') ;
				break ;
			case "U": 
				$("#instructionsContainer").append("<img id='metro' class='directionsIcon' src='https://foursquare.com/img/categories_v2/travel/lightrail_bg_32.png'/><div id='metroLegend' class='legend'></div>") ;
				$("#instructionsContainer").append("<p>At: " + (typeof segment.departure_station_name !== "undefined" ? (segment.departure_station_name + ", ") : ("Waypoint " + (i + 1) + ", ")) + segment.departure_time + "</p>") ;
				$("#instructionsContainer").append("<p>Action: Take the metro " + (typeof segment.number !== "undefined" ? segment.number : "") + (typeof segment.carrier_name !== "undefined" ? (" of carrier " + segment.carrier_name) : "") + "" + (typeof segment.arrival_station_name !== "undefined" ? (" towards " + segment.arrival_station_name) : (" towards Waypoint " + (i + 2))) + (typeof segment.direction !== "undefined" ? (" (direction: " + segment.direction + ")") : "") + "</p>") ;
				$("#instructionsContainer").append("<p>Expected arrival time: " + segment.arrival_time + "</p>") ;
				polylines[i] = createPolyline(latlngs, 'brown') ;
				break ;
			case "GL": 
				$("#instructionsContainer").append("<img id='foot' class='directionsIcon' src='../images/walking.png'/>") ;
				$("#instructionsContainer").append(segment.routino_instructions) ;
				$("#instructionsContainer").append("<p>Expected arrival time: " + segment.arrival_time + "</p>") ;
				polylines[i] = createPolyline(latlngs, 'red') ;
				break ;
		}
		
		if (typeof error !== "undefined") {
			if (error === "routino_error") {
				$("#instructionsContainer").append("<p>ERROR: Routino could not compute the coordinates of the path!</p>") ;
			}else if (error === "coords_error") {
				$("#instructionsContainer").append("<p>ERROR: MobiS could not retrieve the coordinates of the path from the database!</p>") ;
			}
		}
		
		if (i == json.route.length - 1) {
			str = "<p> DESTINATION - " + (typeof segment.departure_station_name !== "undefined" ? ("Waypoint " + (i + 2) + ": " + segment.arrival_station_name) : ("Waypoint " + (i + 2))) + "</p>" ;
			str += "<p>Latitude: " + destLat + "</p>" ;
			str += "<p>Longitude: " + destLng + "</p>" ;
			destinationMarker = createMarker(destLat, destLng, 'blue') ;
			createMarkerMouseOverPopup(destinationMarker, str, false) ;
		}
		else {
			marker = createMarker(destLat, destLng, 'blue') ;
			markers[markers.length] = marker ;
			str = "<p>" + (typeof segment.arrival_station_name !== "undefined" ? ("Waypoint " + (i + 2) + ": " + segment.arrival_station_name) : ("Waypoint " + (i + 2))) + "</p>" ;
			str += "<p>Latitude: " + destLat + "</p>" ;
			str += "<p>Longitude: " + destLng + "</p>" ;
			createMarkerMouseOverPopup(marker, str, false) ;
		}
		$("#instructionsContainer").append("<br>") ;
	}
	var origin = new L.LatLng(originLat, originLng) ;
    var destination = new L.LatLng(destLat, destLng) ;
    var bounds = new L.LatLngBounds(origin, destination) ;
    map.fitBounds(bounds) ;
	isGetDirectionsInitialized = 0 ;
	showContent($("#bigRightContent")) ;
	disablePopup('#popup');
}

/*
function callCarRoutePreferencesHTML() {
	hideLeftContents() ;
	$("#smallTopLeftContent").empty() ;
	var url = "carRoutePreferences.html" ;
	htmlAjaxRequest(url, showCarRoutePreferences) ;
}

function showCarRoutePreferences(data) {
	$("#smallTopLeftContent").append("<div id=\"mediumLeftTitle\"><h1>Route Preferences</h1></div>") ;
    $("#smallTopLeftContent").append(data);
    showCarSharingFields() ;
    showContent($("#smallTopLeftContent")) ;
}

function submitCarRoutePreferences() {
	var shared = $('input:checkbox[name=shareRoute]:checked').val() ;
	if (shared === "true") {
		var name = $("#name").val() ;
		var email = $("#email").val() ;
		var phone = $("#phone").val() ;
		
		if (name && email && phone) {
			var url = "/MobisRoutePlannerV0.3/NewCarSharingRoute?gotCar=1&name=" + name + "&email=" + email + "&phone=" + phone ;
			htmlAjaxRequest(url, showCarRoutePreferencesResponse) ;
		}
	}
}

function showCarRoutePreferencesResponse(data) {
	
}*/
